#!/usr/bin/env python3
"""
Flowable 用户组配置脚本
用于创建流程所需的用户组
"""

import sys
import requests
from requests.auth import HTTPBasicAuth
from typing import List, Dict

# 配置
FLOWABLE_URL = "http://localhost:8080/flowable-ui"
FLOWABLE_REST_URL = "http://localhost:8081/flowable-rest"
FLOWABLE_USER = "admin"
FLOWABLE_PASS = "test"

# 需要创建的用户组
REQUIRED_GROUPS = [
    "project_manager",      # 项目经理组
    "purchase_dept",        # 采购部组
    "finance_dept",         # 财务部组
    "subsidiary_manager",   # 子公司负责人组
    "inventory_manager",    # 库存管理员组
    "direct_manager",       # 直接主管组
    "hr_dept",              # HR部门组
    "admin_manager",        # 行政负责人组
    "leader"                # 领导组
]


class FlowableGroupSetup:
    """Flowable 用户组配置器"""
    
    def __init__(self, rest_url: str, username: str, password: str):
        self.rest_url = rest_url.rstrip('/')
        self.auth = HTTPBasicAuth(username, password)
        self.session = requests.Session()
        self.session.auth = self.auth
    
    def check_service_health(self) -> bool:
        """检查 Flowable 服务是否可用"""
        try:
            url = f"{self.rest_url}/service/management/engine"
            response = self.session.get(url, timeout=5)
            return response.status_code == 200
        except Exception as e:
            print(f"❌ 无法连接到 Flowable 服务: {e}")
            return False
    
    def get_existing_groups(self) -> List[str]:
        """获取已存在的用户组列表"""
        try:
            # 注意：Flowable REST API 可能不直接支持获取组列表
            # 这里需要通过 Identity API 或直接使用 UI
            # 简化处理：假设需要手动在 UI 中创建
            return []
        except Exception as e:
            print(f"⚠️  获取用户组列表失败: {e}")
            return []
    
    def print_setup_instructions(self):
        """打印用户组配置说明"""
        print("\n" + "=" * 60)
        print("Flowable 用户组配置说明")
        print("=" * 60)
        print("\n请在 Flowable UI 中手动创建以下用户组：")
        print(f"\n访问地址: {FLOWABLE_URL}")
        print(f"默认账号: {FLOWABLE_USER} / {FLOWABLE_PASS}")
        print("\n需要创建的用户组：")
        for i, group in enumerate(REQUIRED_GROUPS, 1):
            print(f"  {i}. {group}")
        
        print("\n操作步骤：")
        print("1. 登录 Flowable UI")
        print("2. 进入 '管理' → '用户管理' → '组'")
        print("3. 点击 '创建组'")
        print("4. 依次创建上述用户组")
        print("5. 将实际用户分配到对应的组中")
        print("\n" + "=" * 60)


def main():
    """主函数"""
    print("正在检查 Flowable 服务状态...")
    
    setup = FlowableGroupSetup(FLOWABLE_REST_URL, FLOWABLE_USER, FLOWABLE_PASS)
    
    # 检查服务健康状态
    if not setup.check_service_health():
        print("\n❌ Flowable 服务不可用，请确保服务已启动")
        print(f"   检查地址: {FLOWABLE_REST_URL}")
        sys.exit(1)
    
    print("✅ Flowable 服务连接成功")
    
    # 打印配置说明
    setup.print_setup_instructions()
    
    print("\n✅ 用户组配置说明已生成")
    print("   请按照上述步骤在 Flowable UI 中创建用户组")


if __name__ == "__main__":
    main()

